<template>
  <a-card>
    <div v-if="undoList && undoList.length > 0">
      <a-collapse expandIconPosition="right" v-model="activeKey" v-for="(item, index) in undoList" :key="index" @change="collspanchange">
        <a-collapse-panel :key="String(index + 1)">
          <!-- <a-icon slot="extra" type="delete" class="delete_btn" @click.stop="deleteTodo(item)" title="删除送达详情"/> -->
          <div slot="header" style="display: inline-block;width: 30%;height:48px;padding-top: 12px;padding-left: 16px;" @click.stop="() => {}">
            <a-checkbox @click.stop="checkBoxChange(item)">
              <span @click.stop="() => {}" style="color: #2C2C2C !important;font-size: 16px;font-weight: bold;">{{ item.materialName }}</span>
            </a-checkbox>
          </div>
          <span slot="extra" class="delete_btn" @click.stop="deleteTodo(item)" title="删除送达详情"> <a-icon type="delete" style="margin-right: 10px;" /> 删除送达</span>
          <a-form-model layout="inline">
            <a-row :gutter="48" style="width: 100%; display: flex;align-items: center;">
              <a-col @click.stop="() => {}" :xl="6" :sm="6" :md="4" :lg="4" :xs="24" >
                <a-form-model-item label="提醒:">
                  <div v-if="item.leftDay > 3">
                    <span class="arrive_circle_green"></span>
                    <span class="arrive_label_green"> 剩余  {{ item.leftDay }} 天逾期 </span>
                  </div>
                  <div v-else-if="item.leftDay >= 0 && item.leftDay <= 3">
                    <span class="arrive_circle_orange"></span>
                    <span class="arrive_label_orange"> 剩余  {{ item.leftDay }} 天逾期 </span>
                  </div>
                  <div v-else-if="item.leftDay < 0">
                    <span class="arrive_circle_red"></span>
                    <span class="arrive_label_red"> 延期  {{ Math.abs(item.leftDay) }} 天 </span>
                  </div>
                  <div v-else>
                    <span class="arrive_circle_green"></span>
                    <span class="arrive_label_green"> 暂无提醒 </span>
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col @click.stop="() => {}" :xl="14" :sm="14" :md="14" :lg="14" :xs="24">
                <a-form-model-item label="送达文件:">
                  <div v-if="item.materialList && item.materialList.length > 0">
                    <div v-for="(material, materialIndex) in item.materialList" :key="materialIndex" class="arrive_file">
                      <span @click="fileView(material)" v-if="material.file && material.file.filename"> {{ (material.file && material.file.filename) || '' }}</span>
                      <a-popconfirm title="确定删除吗？" ok-text="确定" cancel-text="取消" @confirm="deleteMaterial(material)">
                        <a-icon type="delete" style="color:#CA0000;margin-left: 10px;" />
                        <!-- <a style="color: #ca0000">删除</a> -->
                      </a-popconfirm>
                    </div>
                  </div>
                </a-form-model-item>
              </a-col>
              <!-- <a-col @click.stop="() => {}" :xl="4" :sm="4" :md="4" :lg="4" :xs="24">
                <a-button class="btn_normal_color" style="height: 24px;float: right;margin-right: 100px;" @click="addPerson(index)" title="添加送达人"> 添加送达人</a-button>
              </a-col> -->
            </a-row>
            <div v-for="(person, personKey) in item.personList" :key="personKey">
              <a-row :gutter="48" style="width: 100%; display: flex;align-items: center;">
                <ArrivePerson :ref="person.id" :key="Math.random()" :recordid="item.id" :personInfo="person" :isEdit="true" @setCache="setPersonCache"
                  @saveSingleTemp="saveSingleTemp"  @deletePerson="deletePerson">
                </ArrivePerson>
              </a-row>
            </div>
          </a-form-model>
          <div class="addPerson_div" @click.prevent="addPerson(index)" title="添加送达人">
            添加送达人
          </div>
        </a-collapse-panel>
      </a-collapse>
    </div>
    <a-empty v-else description="暂无送达信息" style="min-height: 400px" />
  </a-card>
</template>

<script>
import { nanoid } from 'nanoid'
import { kkfilePreview } from '@/utils/util.js'
import { deletePersonById, deleteDetailById, deleteMaterial } from '@/api/arrive/apl_arrive_details'
export default {
  props: {
    applyid: {
      // 申请id
      type: String,
      required: true
    }
  },
  data () {
    return {
      undoList: [],
      leftDay: undefined,
      activeKey: ['1'],
      checkList: []
    }
  },
  async created () {
    this.undoList = this.$store.state.arrive.undoList
    if (this.undoList && this.undoList.length > 0) {
      this.undoList.forEach(undo => {
        const fileItemSet = new Set()
        if (undo.materialList) {
          undo.materialList.forEach(material => {
            fileItemSet.add(material.matttype_text)
          })
        }
        const fileItem = [...fileItemSet]
        undo.materialName = fileItem.join('，')
      })
    }
  },
  mounted () {
    this.$watch(
      () => this.$store.state.arrive.undoList,
      (newValue, oldValue) => {
        this.undoList = newValue
        if (this.undoList && this.undoList.length > 0) {
          this.undoList.forEach(undo => {
            const fileItemSet = new Set()
            if (undo.materialList) {
              undo.materialList.forEach(material => {
                fileItemSet.add(material.matttype_text)
              })
            }
            const fileItem = [...fileItemSet]
            undo.materialName = fileItem.join('，')
          })
        }
      }, { deep: true, immediate: true }
    )
  },
  components: {
    ArrivePerson: () => import('@/views/arrive/ArrivePerson.vue')
  },
  methods: {
    setPersonCache (personForm) {
      if (this.undoList && personForm) {
        for (let fIndex = 0; fIndex < this.undoList.length; fIndex++) {
          const arriveDataObj = this.undoList[fIndex]
          const personList = arriveDataObj.personList
          if (personList) {
            for (let index = 0; index < personList.length; index++) {
              if (personList[index].id == personForm.id) {
                personList[index] = personForm
              }
            }
          }
        }
      }
    },
    addPerson (index) {
      if (this.undoList) {
        const arriveDataObj = this.undoList[index]
        if (arriveDataObj) {
          let personList = arriveDataObj.personList
          if (!personList) {
            personList = []
          }
          personList.push({ 'id': nanoid() })
          for (let index = 0; index < personList.length; index++) {
            if (this.$refs[personList[index].id] && this.$refs[personList[index].id].length > 0) {
              this.$refs[personList[index].id].forEach(refs => {
                const personForm = refs.getPerson()
                personList[index] = personForm
              })
            }
          }
          arriveDataObj.personList = personList
        }
        this.$set(this.undoList, index, arriveDataObj)
        this.$store.commit('SET_UNDO_LIST', this.undoList)
        this.undoList = this.$store.state.arrive.undoList
      }
    },
    fileView (material) {
      window.open(kkfilePreview(material.file.path))
    },
    deletePerson (id) {
      // 后端删除
      deletePersonById(id).then((res) => {
        if (res.code == 0) {
          this.$message.success('删除成功')
          // 前段删除
          if (this.undoList && this.undoList.length > 0) {
          this.undoList.forEach(undo => {
            for (let index = 0; index < undo.personList.length; index++) {
              let personList = undo.personList
              if (personList && personList.length > 0) {
                personList.forEach((person, index) => {
                  if (person.id === id) {
                    personList = personList.filter(el => el.id != id)
                  }
                })
              }
              undo.personList = personList
            }
          })
        }
        this.$store.commit('SET_UNDO_LIST', this.undoList)
        } else {
          this.$message.error('删除失败')
        }
      })
    },
    // 校验表单是否都填写完成
    validateForm () {
      let isValid = true
      if (this.checkList && this.checkList.length > 0) {
        this.checkList.forEach(undo => {
          if (undo.personList && undo.personList.length > 0) {
            undo.personList.forEach(person => {
              if (this.$refs[person.id] && this.$refs[person.id].length > 0) {
                this.$refs[person.id].forEach(refs => {
                  const newValidate = refs.validate()
                  isValid = isValid && newValidate
                })
              }
            })
          }
        })
      } else {
        isValid = false
        this.$message.error('请选择一条数据')
      }
      return isValid
    },
    getUndoList () {
      if (this.undoList && this.undoList.length > 0) {
        this.undoList.forEach(undo => {
          if (undo.personList && undo.personList.length > 0) {
            for (let index = 0; index < undo.personList.length; index++) {
              const person = undo.personList[index]
              if (this.$refs[person.id] && this.$refs[person.id].length > 0) {
                this.$refs[person.id].forEach(refs => {
                  const personForm = refs.getPerson()
                  const newPersonForm = JSON.parse(JSON.stringify(personForm))
                  undo.personList[index] = newPersonForm
                })
              }
            }
          }
        })
      }
      return this.undoList
    },
    getCheckList () {
      if (this.checkList && this.checkList.length > 0) {
        this.checkList.forEach(undo => {
          if (undo.personList && undo.personList.length > 0) {
            for (let index = 0; index < undo.personList.length; index++) {
              const person = undo.personList[index]
              if (this.$refs[person.id] && this.$refs[person.id].length > 0) {
                this.$refs[person.id].forEach(refs => {
                  const personForm = refs.getPerson()
                  const newPersonForm = JSON.parse(JSON.stringify(personForm))
                  undo.personList[index] = newPersonForm
                })
              }
            }
          }
        })
      } else {
        this.$message.error('请选择一条数据')
        return
      }
      return this.checkList
    },

    // 删除一条待送达记录
    deleteTodo (item) {
      const recordId = item.id
      this.$confirm({
        title: '是否删除该数据？',
        onOk: () => {
          deleteDetailById(recordId).then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功')
              this.$emit('reload')
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    // 删除一条材料数据
    deleteMaterial (material) {
      const materialId = material.id
      deleteMaterial(materialId).then(res => {
        if (res.code == 0) {
          this.$message.success('删除成功')
          this.$emit('reload')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    checkBoxChange (item) {
      console.log('选中的数据',item)
      if (this.checkList.some(el => el.id == item.id)) {
        this.checkList = this.checkList.filter(el => el.id != item.id)
      } else {
        this.checkList.push(item)
      }
    },
    saveSingleTemp (detailId) {
      this.$emit('saveSingleTemp', detailId)
    },

    collspanchange () {
    }
  }
}
</script>

<style lang="scss" scoped>

  ::v-deep .ant-collapse {
    background: #ffffff;
    margin-top: 20px;
  }
  ::v-deep .ant-collapse > .ant-collapse-item > .ant-collapse-header {
    font-size: 16px;
    padding: 0px;
  }

  ::v-deep .ant-collapse-header {
    font-size: 16px;
    font-weight: bold;
    background: #F8F8F8;
  }
  ::v-deep .ant-collapse-content > .ant-collapse-content-box {
    padding: 6px 32px;
  }
  .arrive_file {
    display: inline-block;
    margin: 0px 10px;
    cursor: pointer;
    color: #0072C6
  }

  .arrive_delete_btn {
    margin-right: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 24px;
    margin-right: 150px;
  }

  .arrive_circle_red {
    display: inline-block;
    background: #CA0000;
    border-radius: 50%;
    width: 8px;
    height: 8px;
  }
  .arrive_label_red {
    font-family: Source Han Sans CN;
    font-weight: 500;
    font-size: 14px;
    color: #CA0000;
    margin-left: 10px;
    margin-right: 30px;
  }

  .arrive_circle_orange {
    display: inline-block;
    background: #FFA200;
    border-radius: 50%;
    width: 8px;
    height: 8px;
  }
  .arrive_label_orange {
    font-family: Source Han Sans CN;
    font-weight: 500;
    font-size: 14px;
    color: #FFA200;
    margin-left: 10px;
    margin-right: 30px;
  }
  .arrive_circle_green {
    display: inline-block;
    background: #00AE08;
    border-radius: 50%;
    width: 8px;
    height: 8px;
  }
  .arrive_label_green  {
    font-family: Source Han Sans CN;
    font-weight: 500;
    font-size: 14px;
    color: #00AE08;
    margin-left: 10px;
    margin-right: 30px;
  }

  .delete_btn {
    font-family: Source Han Sans CN;
    font-weight: 800;
    font-size: 16px;
    color: #0072C6;
    display: flex;
    align-items: center;
    justify-content: space-around;
    margin-right: 80px;
    padding-top: 12px;
  }
  .addPerson_div {
    background: #FFFFFF;
    border: 1px dashed #BCC4D2;
    opacity: 0.65;
    height: 40px;
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: Source Han Sans CN;
    font-size: 16px;
    color: #030F1D;
    opacity: 0.55;
    cursor: pointer;
    margin-left: -12px;
    margin-right: 30px;
  }
</style>
